package org.hcyspartnoc.demo.common.core.interceptors;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hcyspartnoc.demo.common.exception.common.CommonUtilsException;
import org.hcyspartnoc.demo.utils.RequestUtil;
import org.hcyspartnoc.demo.utils.redis.RedisComponent;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class VisitInterceptor implements HandlerInterceptor {
    @Resource
    private RedisComponent redisComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (redisComponent.isMaxVisitLimit(RequestUtil.getIp()))
            throw new CommonUtilsException(CommonUtilsException.VISIT_TOO_BUSY);
        redisComponent.incrementVisitLimit(RequestUtil.getIp());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
